package com.apotik.legenda.dialog;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;

import com.apotik.legenda.bean.TrxUniqueNumberBean;
import com.apotik.legenda.dao.CardDao;
import com.apotik.legenda.dao.InsuranceDao;
import com.apotik.legenda.dao.ProductDao;
import com.apotik.legenda.dao.SalesTrxDao;
import com.apotik.legenda.dao.SalesTrxObatDao;
import com.apotik.legenda.dao.TransactionUniqueNumberDao;
import com.apotik.legenda.model.Card;
import com.apotik.legenda.model.Insurance;
import com.apotik.legenda.model.Product;
import com.apotik.legenda.model.SalesTrx;
import com.apotik.legenda.model.SalesTrxObat;
import com.apotik.legenda.model.TransactionUniqueNumber;
import com.apotik.legenda.observer.PosObserver;
import com.apotik.legenda.util.AppUtil;
import com.apotik.legenda.util.PrinterUtil;

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.Toolkit;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;

import javax.swing.DefaultComboBoxModel;
import javax.swing.JDialog;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JOptionPane;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.JButton;
import javax.swing.border.EtchedBorder;
import javax.swing.SwingConstants;

import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;

public class BayarDialog extends JDialog implements KeyListener, ActionListener, FocusListener {
	private static final long serialVersionUID = 1L;
	
	private PosObserver observer;
	private SalesTrx st;
	private List<Insurance> insuranceList;
	private List<Card> cardList;
	
	private JTextField textFieldTotal;
	private JTextField textFieldBayar;
	private JTextField textFieldKembali;
	
	private JButton btnOk;
	private JButton btnCancel;
	
	@SuppressWarnings("rawtypes")
	private JComboBox comboBoxPayment;
	@SuppressWarnings("rawtypes")
	private JComboBox comboBoxAsr;
	@SuppressWarnings("rawtypes")
	private JComboBox comboBoxCard;
	
	
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public BayarDialog(PosObserver observer, SalesTrx st) {
		this.observer = observer;
		this.st = st;
		
		int widthFrame = 400;
		
		setTitle("Bayar");
		setSize(widthFrame, 350);
		setDefaultCloseOperation(JDialog.DO_NOTHING_ON_CLOSE);
		addKeyListener(this);
		
		Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
		setLocation((dim.width-widthFrame)/2, 100);
		
		JPanel panel = new JPanel();
		panel.setBorder(new EmptyBorder(5, 5, 5, 5));
		panel.setLayout(new BorderLayout(0, 4));
		getContentPane().add(panel, BorderLayout.CENTER);
		
		JPanel panelNorth = new JPanel();
		panel.add(panelNorth, BorderLayout.NORTH);
		panelNorth.setBorder(new EtchedBorder(EtchedBorder.LOWERED, null, null));
		panelNorth.setLayout(new BorderLayout(0, 0));
		
		JPanel panel_1 = new JPanel();
		panel_1.setBorder(new EmptyBorder(5, 5, 5, 5));
		panelNorth.add(panel_1);
		panel_1.setLayout(new GridLayout(0, 2, 0, 4));
		
		JLabel lblPayment = new JLabel("Pembayaran");
		panel_1.add(lblPayment);
		lblPayment.setFont(new Font("Tahoma", Font.PLAIN, 15));
		
		comboBoxPayment = new JComboBox(new DefaultComboBoxModel(new String[] {AppUtil.PAYMENT_BY_TUNAI, AppUtil.PAYMENT_BY_CARD, AppUtil.PAYMENT_BY_ASRNSI}));
		panel_1.add(comboBoxPayment);
		comboBoxPayment.setFont(new Font("Tahoma", Font.PLAIN, 13));
		comboBoxPayment.setSelectedIndex(0);
		comboBoxPayment.addActionListener(this);
		
		JLabel lblAsr = new JLabel("Asuransi");
		panel_1.add(lblAsr);
		lblAsr.setEnabled(false);
		lblAsr.setFont(new Font("Tahoma", Font.PLAIN, 15));
		
		comboBoxAsr = new JComboBox();
		comboBoxAsr.setModel(modelsAsr());
		panel_1.add(comboBoxAsr);
		comboBoxAsr.setFont(new Font("Tahoma", Font.PLAIN, 13));
		comboBoxAsr.setEnabled(false);
		comboBoxAsr.addKeyListener(this);
		
		JLabel lblCard = new JLabel("Card");
		panel_1.add(lblCard);
		lblCard.setEnabled(false);
		lblCard.setFont(new Font("Tahoma", Font.PLAIN, 15));
		
		comboBoxCard = new JComboBox();
		comboBoxCard.setModel(modelsCard());
		panel_1.add(comboBoxCard);
		comboBoxCard.setEnabled(false);
		comboBoxCard.setFont(new Font("Tahoma", Font.PLAIN, 13));
		
		JPanel panelCenter = new JPanel();
		panel.add(panelCenter, BorderLayout.CENTER);
		panelCenter.setBorder(new EtchedBorder(EtchedBorder.LOWERED, null, null));
		panelCenter.setLayout(new BorderLayout(0, 0));
		
		JPanel panel_2 = new JPanel();
		panel_2.setBorder(new EmptyBorder(5, 5, 5, 5));
		panel_2.setLayout(new GridLayout(0, 2, 0, 4));
		panelCenter.add(panel_2);
		
		JLabel lblBayar = new JLabel("Bayar");
		lblBayar.setFont(new Font("Tahoma", Font.PLAIN, 23));
		panel_2.add(lblBayar);
		
		textFieldBayar = new JTextField();
		textFieldBayar.setHorizontalAlignment(SwingConstants.RIGHT);
		textFieldBayar.setFont(new Font("Tahoma", Font.PLAIN, 19));
		textFieldBayar.setColumns(10);
		textFieldBayar.addKeyListener(this);
		textFieldBayar.addActionListener(this);
		textFieldBayar.addFocusListener(this);
		panel_2.add(textFieldBayar);
		
		JLabel lblTotal = new JLabel("Total");
		panel_2.add(lblTotal);
		lblTotal.setFont(new Font("Tahoma", Font.PLAIN, 23));
		
		textFieldTotal = new JTextField();
		textFieldTotal.setEditable(false);
		textFieldTotal.setHorizontalAlignment(SwingConstants.RIGHT);
		textFieldTotal.setFont(new Font("Tahoma", Font.PLAIN, 19));
		textFieldTotal.setColumns(10);
		textFieldTotal.setText(AppUtil.formatStringIDR(st.getAmountTrx().intValue()));
		panel_2.add(textFieldTotal);
		
		JLabel lblKembali = new JLabel("Kembali");
		lblKembali.setFont(new Font("Tahoma", Font.PLAIN, 23));
		panel_2.add(lblKembali);
		
		textFieldKembali = new JTextField();
		textFieldKembali.setEditable(false);
		textFieldKembali.setHorizontalAlignment(SwingConstants.RIGHT);
		textFieldKembali.setFont(new Font("Tahoma", Font.PLAIN, 19));
		textFieldKembali.setColumns(10);
		panel_2.add(textFieldKembali);
		
		JPanel panelSouth = new JPanel();
		panel.add(panelSouth, BorderLayout.SOUTH);
		
		btnOk = new JButton("Print");
		btnOk.setFont(new Font("Tahoma", Font.PLAIN, 13));
		btnOk.addActionListener(this);
		panelSouth.add(btnOk);
		
		btnCancel = new JButton("Cancel");
		btnCancel.addActionListener(this);
		panelSouth.add(btnCancel);
		
		
	}
	
	@SuppressWarnings("rawtypes")
	private DefaultComboBoxModel modelsAsr(){
		InsuranceDao dao = new InsuranceDao();
		Criterion cr1 = Restrictions.eq("isActive", true);
		List<Insurance> list = dao.loadBy(Order.asc("insuranceName"), cr1);
		insuranceList = list;
		
		String[] data = new String[list.size()];
		for(int i=0;i<list.size();i++){
			Insurance obj = list.get(i);
			data[i] = obj.getInsuranceName();
		}
		
		DefaultComboBoxModel model = new DefaultComboBoxModel<>(data);
		return model;
	}
	
	@SuppressWarnings("rawtypes")
	private DefaultComboBoxModel modelsCard(){
		CardDao dao = new CardDao();
		List<Card> list = dao.loadAll(Order.asc("cardName"));
		cardList = list;
		
		String[] data = new String[list.size()];
		for(int i=0;i<list.size();i++){
			Card obj = list.get(i);
			data[i] = obj.getCardName();
		}
		
		DefaultComboBoxModel model = new DefaultComboBoxModel<>(data);
		return model;
	}
	
	private void btnSubmitAction(){
		TrxUniqueNumberBean tunb = AppUtil.generateTrxUniqueNumber("T");
		if(tunb==null){
			JOptionPane.showMessageDialog(null, "Generate Nomor Nota error", "Error", JOptionPane.ERROR_MESSAGE);
		}else{
			int dialogPrint = JOptionPane.showConfirmDialog(null, "Apakah yakin ingin melanjutkan Print?", "Print", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);

			TransactionUniqueNumber tun = new TransactionUniqueNumber();
			tun.setUniqueNumberId(tunb.getId());
			tun.setCode(tunb.getCode());
			tun.setNumber(tunb.getNumber());
			tun.setMonth(tunb.getMonth());
			tun.setYear(tunb.getYear());
			
			TransactionUniqueNumberDao tunDao = new TransactionUniqueNumberDao();
			tunDao.saveOrUpdate(tun);
			
			String paymentBy = (String) comboBoxPayment.getSelectedItem();
			String asuransiFrom = null;
			String cardFrom = null;
			if(paymentBy.equalsIgnoreCase(AppUtil.PAYMENT_BY_ASRNSI)){
				int index = comboBoxAsr.getSelectedIndex();
				if(insuranceList.size()>0){
					Insurance obj = insuranceList.get(index);
					asuransiFrom = obj.getInsuranceName();
				}
			}else if(paymentBy.equalsIgnoreCase(AppUtil.PAYMENT_BY_CARD)){
				int index = comboBoxCard.getSelectedIndex();
				if(cardList.size()>0){
					Card obj = cardList.get(index);
					cardFrom = obj.getCardName();
				}
			}
			
			SalesTrx st = this.st;
			st.setTrxCode(tunb.getUniqueNumber());
			st.setPaymentStatus(AppUtil.TRANSAKSI_STATUS_BAYAR);
			st.setPaymentBy(paymentBy);
			st.setAsuransiFrom(asuransiFrom);
			st.setCardFrom(cardFrom);
			
			//updateStok(st);//coba
			
			SalesTrxDao dao = new SalesTrxDao();
			if(dao.saveOrUpdate(st)){
				updateStok(st);
				
				HashMap<String, Object> hm = new HashMap<>();
				hm.put("salesTrx", st);
				observer.bayar(hm);
				
				if(dialogPrint==JOptionPane.YES_OPTION){
					PrinterUtil.printTransaction(st);
				}
				
				BayarDialog.this.setVisible(false);
			}
		}
	}
	
	private void updateStok(SalesTrx st){
		SalesTrxObatDao dao = new SalesTrxObatDao();
		List<SalesTrxObat> list = dao.listBySalesTrx(st);
		
		for(SalesTrxObat obj: list){
			int qty = obj.getQuantity();
			Product product = obj.getProduct();
			
			int stokUpdate = product.getAvailableStock() - qty;
			product.setAvailableStock(stokUpdate);
			
			ProductDao productDao = new ProductDao();
			productDao.saveOrUpdate(product);
		}
	}
	
	@Override
	public void actionPerformed(ActionEvent ae) {
		Object obj = ae.getSource();
		
		if(obj==comboBoxPayment){
			String item = (String) comboBoxPayment.getSelectedItem();
			if(item.equalsIgnoreCase(AppUtil.PAYMENT_BY_TUNAI)){
				comboBoxAsr.setEnabled(false);
				comboBoxCard.setEnabled(false);
			}else if(item.equalsIgnoreCase(AppUtil.PAYMENT_BY_ASRNSI)){
				comboBoxAsr.setEnabled(true);
				comboBoxCard.setEnabled(false);
			}else if(item.equalsIgnoreCase(AppUtil.PAYMENT_BY_CARD)){
				comboBoxAsr.setEnabled(false);
				comboBoxCard.setEnabled(true);
			}
		}else if(obj==btnOk){
			btnSubmitAction();
		}else if(obj==btnCancel){
			BayarDialog.this.setVisible(false);
		}
	}

	@Override
	public void keyPressed(KeyEvent ke) {
		Object obj = ke.getSource();
		
		/*if(ke.getKeyCode()==KeyEvent.VK_ESCAPE){
			this.setVisible(false);
		}*/
		
		if(obj==textFieldBayar){
			if(ke.getKeyCode()==KeyEvent.VK_ENTER){
				btnOk.requestFocus();
			}
		}else if(obj==btnOk){
			if(ke.getKeyCode()==KeyEvent.VK_ENTER){
				btnSubmitAction();
			}
		}else if(obj==btnCancel){
			if(ke.getKeyCode()==KeyEvent.VK_ENTER){
				BayarDialog.this.setVisible(false);
			}
		}
	
	}

	@Override
	public void keyReleased(KeyEvent ke) {
		/*Object obj = ke.getSource();
		
		if(obj==textFieldBayar){
			if(ke.getKeyCode()==KeyEvent.VK_0 || ke.getKeyCode()==KeyEvent.VK_1 || ke.getKeyCode()==KeyEvent.VK_2 || 
					ke.getKeyCode()==KeyEvent.VK_3 || ke.getKeyCode()==KeyEvent.VK_4 || ke.getKeyCode()==KeyEvent.VK_5 || 
					ke.getKeyCode()==KeyEvent.VK_6 || ke.getKeyCode()==KeyEvent.VK_7 || ke.getKeyCode()==KeyEvent.VK_8 || 
					ke.getKeyCode()==KeyEvent.VK_9 || ke.getKeyCode()==KeyEvent.VK_BACK_SPACE || ke.getKeyCode()==KeyEvent.VK_DELETE){
				
				String valStr = textFieldBayar.getText();
				if(valStr.trim().isEmpty()){
					valStr = "0";
				}

				String removeDot = AppUtil.removeCharacters(valStr, ".");
				
				BigDecimal input = new BigDecimal(removeDot);				
				BigDecimal total = st.getAmountTrx();
				BigDecimal kembali = input.subtract(total);
				
				textFieldKembali.setText(AppUtil.formatStringIDR(kembali.intValue()));
			}
		}*/
	}

	@Override
	public void keyTyped(KeyEvent ke) {
		// TODO Auto-generated method stub
	}
	
	@Override
	public void focusGained(FocusEvent e) {
		Object source = e.getSource();
		
		if(source==textFieldBayar){
			String valStr = textFieldBayar.getText();
			if(valStr.trim().isEmpty()) valStr = "0";
			
			String removeDot = AppUtil.removeCharacters(valStr, ".");
			textFieldBayar.setText(removeDot);
		}
	}
	
	@Override
	public void focusLost(FocusEvent e) {
		Object source = e.getSource();
		
		if(source==textFieldBayar){
			String valStr = textFieldBayar.getText();
			if(valStr.trim().isEmpty()) valStr = "0";
			int valInt = Integer.parseInt(valStr);
			
			textFieldBayar.setText(AppUtil.formatStringIDR(valInt));
			
			BigDecimal input = new BigDecimal(valInt);				
			BigDecimal total = st.getAmountTrx();
			BigDecimal kembali = input.subtract(total);
			
			textFieldKembali.setText(AppUtil.formatStringIDR(kembali.intValue()));
		}
	}
	
}
